package com.wr.controllers;

import com.wr.pojos.RoleEntity;
import com.wr.pojos.UserEntity;
import com.wr.services.RoleService;
import com.wr.utils.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @RequestMapping("/roleList")
    public String roleList(PageInfo pageInfo, Model model){
        List<RoleEntity> list = roleService.selectRoleList(pageInfo);
        model.addAttribute("list",list);
        return "layui/roleManage/role_list";
    }

    @RequestMapping("/editRole")
    @ResponseBody
    public Map<String,Object> editRole(@RequestParam(value = "array[]",defaultValue = "")int array[],int roleId){
        Map<String,Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        UserEntity userEntity = (UserEntity) subject.getPrincipal();
        if(!"1".equals(userEntity.getId())){
            map.put("result","failed");
            return map;
        }
        roleService.saveRolePermission(array, roleId);
        map.put("result","success");
        return map;
    }

    @RequestMapping("/saveRole")
    @ResponseBody
    public Map<String,Object> saveRole(@RequestParam(value = "array[]",defaultValue = "")int array[],RoleEntity roleEntity){
        Map<String,Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        UserEntity userEntity = (UserEntity) subject.getPrincipal();
        roleEntity.setOperationId(userEntity.getId());
        roleService.insertRole(array,roleEntity);
        map.put("result","success");
        return map;
    }
}
